import EventDispatcher from "../../event/EventDispatcher"
import NetConfig from "../NetConfig"
import Message from "../message/Message";
import ServiceInterface from "./ServiceInterface";
/**
 * 统一长连接和短连接的接口。
 */
export default abstract class Service  extends EventDispatcher implements ServiceInterface{

    protected state : string = NetConfig.CLOSED;

    protected url:string;

    protected port:number;

    protected messageList:Array<any>;

    private pushFlag:boolean = false;

    constructor(){
        super();
        this.messageList = [];
    }

    connect(url:string,port?:number){
        this.url = url;
        this.port = port;
        this.pushFlag = false;
    }
    //手动重联
    reConnect(){
        
    }
    /**
     * 服务是否准备好 短连接协议直接返回true。
     */
    isReady(){
        return this.state == NetConfig.OPEN;
    }

    getState(){
        return this.state;
    }

   /**
     * 发送数据调用，子类实现自己的细节。
     * @param message 需要发送的消息
     */
    sendData(message: Message){
    }

    destroy():void{
    }   
   /**
     * 连接打开 短连接直接调用该函数 统一使用方式。
     * @param data 
     */
    onOpen(data?){
        this.state = NetConfig.OPEN;
        this.publish(NetConfig.OPEN,data);
    }  

    onData(data,protoID?:string|number){
        this.publish(NetConfig.DATA,data,protoID); 
    }

    pushData(data,protoID){
        this.messageList.push({protoID:protoID,data:data});
    }

    popData(){
        if(!this.pushFlag &&this.messageList.length > 0){
            return this.messageList.shift();
        }
        return null;
    }
    
    onError(data?){
        this.state = NetConfig.ERROR;
        this.publish(NetConfig.ERROR,data);
    }

    onClose(data?){
        this.state = NetConfig.CLOSED;
        this.publish(NetConfig.CLOSED,data);
    }  
}
